package com.bite.lesson1;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;

    private String serverIp;

    private int serverPort;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {

        socket = new DatagramSocket();

        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动......");
        while(true) {
            Scanner scanner = new Scanner(System.in);
            String request = scanner.nextLine();
            if (request == null || request.isEmpty()) {
                System.out.println("输入错误......");
                continue;
            }
            //确定目的地址
            SocketAddress address = new InetSocketAddress(serverIp,serverPort);

            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),0,request.getBytes().length,address);
            socket.send(requestPacket);

            DatagramPacket responsePocket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePocket);

            String response = new String(responsePocket.getData(),0,responsePocket.getLength(),"UTF-8");
            System.out.printf("request = %s, response = %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",8888);
        client.start();
    }
}
